<template>
    <coreshop-page bgColor="rgba(0,0,0,0)" :isShowStatusBarHeight="false" :placeholder="false" showLoginModalDom
        needLoadingPage :loadingPage="loadingPage">
        <view class="goods-detail">
            <!-- 商品详情 -->
            <GoodsDetail :goodsId="state.goodsDetailData?.id" :goodsDetailData="state.goodsDetailData"
                :swiperBanner="state.swiperBanner" :shareType="ShareEnum.pinTuan"
                :goodsDetailContent="state.goodsDetailContent" :isActivityGoods="true">
                <template #activityGoodsOtheService>
                    <view class="pinTuan-record" v-if="state.goodsDetailData?.pinTuanRecord?.length > 0">
                        <view class="title">
                            <view class="tit">开团信息</view>
                            <view class="desc">{{ state.goodsDetailData?.pinTuanRecordNums || '0' }}人在拼单，可直接参与</view>
                        </view>
                        <view class="pinTuan-box">
                            <view class="item-box" v-for="item, index in state.goodsDetailData?.pinTuanRecord"
                                :key="index">
                                <view class="msg-box">
                                    <view class="msg">还差 <text class="red">{{ item.teamNums || '' }}人</text> 拼成</view>
                                    <view class="time">
                                        剩余：
                                        <uv-count-down :time="item.lastTime * 1000" format="HH:mm:ss"></uv-count-down>
                                    </view>
                                </view>
                                <view class="peo-box">
                                    <image class="peo" v-for="cell, cellIndex in item.teams" :key="cellIndex"
                                        :src="cell.userAvatar"></image>
                                </view>
                                <view class="peo-share">
                                    <uv-button v-if="item.isOverdue" type="success" :disabled="true" size="mini"
                                        text="已结束"></uv-button>
                                    <uv-button v-else type="success" size="mini" text="去拼单"
                                        @click="handleSplicingOrders(item.teamId)"></uv-button>
                                </view>
                            </view>
                        </view>
                    </view>
                </template>
            </GoodsDetail>

            <!-- 为您推荐 -->
            <GoodsDetailRecommend></GoodsDetailRecommend>

            <!-- 底部 购买 -->
            <GoodsDetailBottomTabbar>
                <template #bottomTabbar>
                    <view class="btn-box">
                        <view class="btn" @click="handleSingleBuy">
                            <view class="box">
                                <view class="num">￥{{ state.goodsDetailData.price }}</view>
                                <view class="tit">单独购买</view>
                            </view>
                        </view>
                        <view class="btn buy" @click="handleMultipleBuy()">
                            <view class="box">
                                <view class="num">￥{{ state.goodsDetailData.pinTuanPrice }}</view>
                                <view class="tit">发起拼团</view>
                            </view>
                        </view>
                    </view>
                </template>
            </GoodsDetailBottomTabbar>

            <!-- 商品sku弹框 -->
            <GoodsDetailSkuPopup :showSku="state.showSku" :goodsDetailData="state.goodsDetailData"
                :isShowAddCartBtn="false" :buyNowNowloading="loading" @handleChangePopup="handleChangePopup"
                @handleBuyNow="handleBuyNow" :btnBuyTitlt="state.btnBuyTitlt">
            </GoodsDetailSkuPopup>
            
            <!-- 分享进来的参与拼团弹框 -->
            <uv-popup ref="pinTuanPopup" mode="bottom" :closeable="true">
                <view class="pinTuan-popup-box">
                    <view class="time-title">剩余时间：</view>
                    <view class="time">
                        <uv-count-down :time="state.teamInfo.lastTime * 1000" :autoStart="true" :millisecond="true" format="DD天HH时mm分ss秒"></uv-count-down>
                    </view>
                    <view class="teams-box">
                        <view class="img-box" v-for="item,index in state.teamInfo.teams" :key="index">
                            <text class="tit" v-if="item.recordId == item.teamId">拼主</text>
                            <image class="img" :src="item.userAvatar"></image>
                        </view>
                        <view class="need-peo" v-if="state.teamInfo?.teamNums" v-for="item in state.teamInfo?.teamNums" :key="item">
                            <text class="tit">?</text>
                        </view>
                    </view>
                    <view class="peo-box">
                        还差 <text class="peo">{{ state.teamInfo?.teamNums || '' }}</text> 人，赶快拼单吧
                    </view>
                    <view class="btn-box" @click="handleJoinGroupBuy">
                        参与拼团
                    </view>
                </view>
            </uv-popup>
        </view>
    </coreshop-page>
</template>
<script setup lang="ts">
    import { reactive, ref } from 'vue';
    import { onLoad, onShareAppMessage, onShareTimeline, onPullDownRefresh } from '@dcloudio/uni-app';
    import { queryPinTuanGoodsDetail, queryCartNum, queryAddCart, queryOrderPinTuanTeamInfo } from '@/core/api';
    import type { Response } from '@/core/models';
    import { UserToken, shareUrl } from '@/core/consts'
    import { useCartStore, useLoginStore } from '@/core/store';
    import { PaymentTypeEnum, ShareEnum, ShareClientEnum, ShareModelEnum } from '@/core/enum';
    import { handleRouteNavigateTo, handleShowToast, getShareUrl } from '@/core/utils';
    import { deepClone } from '@/uni_modules/uv-ui-tools/libs/function/index.js';

    import GoodsDetail from '@/pages/components/goods-detail/index.vue';
    import GoodsDetailRecommend from '@/pages/components/goods-detail/components/goods-detail-recommend/goods-detail-recommend.vue';
    import GoodsDetailSkuPopup from '@/pages/components/goods-detail/components/goods-detail-sku/goods-detail-sku.vue';
    import GoodsDetailBottomTabbar from '@/pages/components/goods-detail/components/goods-detail-bottom-tabbar/goods-detail-bottom-tabbar.vue';
    import { useLoadingFn } from '@/core/hooks';

    interface QueryParams {
        id : number;
        teamId ?: number;
    }

    /** 登录store */
    const _useLoginStore = useLoginStore();

    /** 获取购物车数据 */
    const cartStore = useCartStore();
    
    /** 分享进来的参与拼团弹框 */
    const pinTuanPopup = ref();
    
    const state = reactive<{
        id : number;
        goodsDetailData : any,
        swiperBanner : Array<string>;
        goodsDetailContent : string;
        skuPrice : Number;
        defaultSkuList : Array<any>;
        activitySkuList : Array<any>;
        showSku : boolean;
        teamId : number;
        isSingleBuy : boolean;
        btnBuyTitlt : string;
        teamInfo : any;
        shareUrl : string;
    }>({
        id: 0,
        goodsDetailData: {},
        swiperBanner: [],
        goodsDetailContent: "",
        skuPrice: 0,
        defaultSkuList: [],
        activitySkuList: [],
        showSku: false,
        teamId: 0,
        isSingleBuy: true,
        btnBuyTitlt: "发起拼团",
        teamInfo: {},
        shareUrl: "",
    });

    const loading = ref(false);
    const loadingPage = ref(true);
    const handleBuyNow = useLoadingFn(onBuyNow, loading);
    const handleGetGoodsDetail = useLoadingFn(getGoodsDetail, loadingPage);

    onLoad((query : QueryParams) => {
        if (query?.teamId) {
            state.teamId = query?.teamId;
            state.goodsDetailData = {
                teamId: query?.teamId
            };
            getOrderPinTuanTeamInfo(query?.teamId);
        }
        /** 获取商品详情 */
        state.id = Number(query.id);
        handleGetGoodsDetail();
    });

    onPullDownRefresh(async () => {
        await handleGetGoodsDetail();
        uni.stopPullDownRefresh();
    });

    async function getGoodsDetail() {
        let data = {
            id: state.id,
            data: true,
        }
        if (uni.getStorageSync(UserToken)) {
            data['token'] = uni.getStorageSync(UserToken)
        }
        const goodsDetail : Response<any> = await queryPinTuanGoodsDetail(data);

        /** 增加活动价格，并合并对象，可能会存在 teamId */
        Object.assign(state.goodsDetailData, {
            ...goodsDetail.data,
            activityPrice: goodsDetail.data.pinTuanPrice,
        });

        /** 默认价格 */
        state.skuPrice = goodsDetail?.data?.price;
        /** 商品轮播图 */
        state.swiperBanner = goodsDetail?.data?.images?.split(',');
        /** 商品详情内容 */
        state.goodsDetailContent = goodsDetail?.data?.intro;
        /** 默认sku */
        state.defaultSkuList = deepClone(goodsDetail?.data?.skuList?.sku_list);
        /** 活动商品价格sku */
        state.activitySkuList = deepClone(state.goodsDetailData?.skuList?.sku_list?.map((item : any) => {
            item.price = (Number(item.price) - Number(state.goodsDetailData.pinTuanRule.discountAmount));
            return item;
        }));
        /** 如果用户登录，获取购物车数量 */
        if (uni.getStorageSync(UserToken)) {
            getCartNum();
        }
        state.shareUrl = await getShareUrl({
            client: ShareClientEnum.wxMiNiProgram,
            url: shareUrl,
            type: ShareModelEnum.url,
            page: ShareEnum.pinTuan,
            params: {
                groupId: state.id,
                goodsId: state.goodsDetailData.id,
                teamId: state.teamId
            }
        })
    }

    /** 获取通过分享进来的拼团数据 */
    const getOrderPinTuanTeamInfo = async (teamId : number) => {
        const teamInfo : Response<any> = await queryOrderPinTuanTeamInfo({ teamId, });
        if (teamInfo.status) {
            state.teamInfo = teamInfo?.data;
            pinTuanPopup.value.open();
        } else {
            handleShowToast(teamInfo.msg)
        }
    }
    /** 获取购物车数量 */
    const getCartNum = async () => {
        const num : Response<number> = await queryCartNum();
        cartStore.setCartNum(num?.data || 0);
    }
    
    /** 单独购买 */
    const handleSingleBuy = () => {
        _useLoginStore.checkLogin(() => {
            state.teamId = 0;
            state.showSku = true;
            state.isSingleBuy = true;
            state.btnBuyTitlt = '单独购买';
            state.goodsDetailData.skuList.sku_list = state.defaultSkuList;
        });
    }
    
    /** 拼团购买统一调用 */
    const handlePinTuan = (title?:string)=>{
        _useLoginStore.checkLogin(() => { 
            state.showSku = true;
            state.isSingleBuy = false;
            state.btnBuyTitlt = title || '发起拼团';
            state.goodsDetailData.skuList.sku_list = state.activitySkuList;
        });
    }
    
    /** 弹框中的按钮参与拼团购买 */
    const handleJoinGroupBuy = ()=>{
        pinTuanPopup.value.close();
        handlePinTuan('参与拼团');
    } 
    
    /** 拼团购买 */
    const handleMultipleBuy = () => {
        state.teamId = 0;
        handlePinTuan()
    }

    /** 去拼单购买 */
    const handleSplicingOrders = (teamId : number) => {
        state.teamId = teamId;
        handlePinTuan('去拼单');
    } 
    
    /** 关闭sku弹框 */
    const handleChangePopup = (show : boolean) => {
        state.showSku = show;
    }

    /** 立即购买购买 */
    async function onBuyNow({ productId, nums } : any) {
        if (state.isSingleBuy) {
            await handleSingleQuery(productId, nums)
        } else {
            await handleMultipleQuery(productId, nums)
        }
    }

    /** 处理单个购买请求 */
    const handleSingleQuery = async (productId : number, nums : number) => {
        const addCart : Response<number> = await queryAddCart({
            ProductId: productId,
            Nums: nums,
            type: PaymentTypeEnum.pinTuan,
            cartType: PaymentTypeEnum.common,
        });
        if (addCart.status) {
            handleRouteNavigateTo(`/pages/order/submit/submit?cartIds=${addCart.data}`)
            /** 关闭sku弹框 */
            handleChangePopup(false);
        } else {
            handleShowToast(addCart.msg);
        }
    }

    /** 处理拼团购买请求 */
    const handleMultipleQuery = async (productId : number, nums : number) => {
        const addCart : Response<number> = await queryAddCart({
            ProductId: productId,
            Nums: nums,
            type: PaymentTypeEnum.pinTuan,
            cartType: PaymentTypeEnum.pinTuan,
            objectId: state.id,
            teamId: state.teamId
        });
        if (addCart.status) {
            handleRouteNavigateTo(`/pages/order/submit/submit?cartIds=${addCart.data}&orderType=${PaymentTypeEnum.pinTuan}&objectId=${state.id}${state.teamId != 0 ? `&teamId=${state.teamId}` : ''}`)
            /** 关闭sku弹框 */
            handleChangePopup(false);
        } else {
            handleShowToast(addCart.msg);
        }
    }

    /** 分享 */
    onShareAppMessage(() => {
        return {
            title: state.goodsDetailData.name,
            imageUrl: state.goodsDetailData.image,
            path: state.shareUrl
        }
    });
    onShareTimeline(() => {
        return {
            title: state.goodsDetailData.name,
            imageUrl: state.goodsDetailData.image,
            path: state.shareUrl
        }
    });
</script>
<style lang="scss" scoped>
    @import './detail.scss';
</style>